package com.enation.app.javashop.consumer.shop.shop;

import com.enation.app.javashop.consumer.core.event.ShopTagChangeEvent;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.goods.model.dto.TagsDTO;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zhou
 * @Date: 2020/12/10
 * @Description: 查询店铺中关联所有商品的标签，并放入redis
 */
@Component
public class ShopTagChangeConsumer implements ShopTagChangeEvent {

    @Autowired
    @Qualifier("goodsDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private Cache cache;

    @Override
    public void shopTagChangeCache(List<Integer> sellerIds) {
        if(!CollectionUtils.isEmpty(sellerIds)){
            // 1、查询所有店铺的启用中且关联所有商品的标签
            String sql = "select * from es_tags where seller_id in (?) and `status` = 0 and all_goods=0";
            List<TagsDTO> allGoodsTagList = this.daoSupport.queryForList(sql, TagsDTO.class, StringUtil.listToString(sellerIds,","));

            if(!CollectionUtils.isEmpty(allGoodsTagList)){
                // 2、分组放入redis
                Map<Integer,List<TagsDTO>> sellerTagsMap=allGoodsTagList.stream().collect(Collectors.groupingBy(TagsDTO::getSellerId, Collectors.toList()));
                for(Integer sellerId:sellerIds){
                    cache.put(CachePrefix.SHOP_TAG.getPrefix() + sellerId, sellerTagsMap.get(sellerId));
                }
            }
        }
    }
}
